# -*- coding: utf-8 -*-

from app import app

class MySQLConnector:

    def get_con(self):
        try:
            if hasattr(app, "cnx_pool"):
                con = app.cnx_pool.get_connection()
        except Exception as e:
            print(e)
            if "con" in dir():
                con.close()
                return None
        return con

    def release_con(self, con, cur):
        if cur:
            cur.close()
        if "con" in dir():
            con.close()

    def op_query_one(self, sql):
        result = None
        msg = ""
        try:
            con = self.get_con()
            cur = con.cursor(dictionary=True)
            cur.execute(sql)
            result = cur.fetchone()
        except Exception as e:
            print(e)
            msg = e.__str__()
        finally:
            self.release_con(con, cur)
        return result, msg

    def op_query(self, sql, is_dictionary=True):
        result = None
        msg = ""
        try:
            con = self.get_con()
            cur = con.cursor(dictionary=is_dictionary)
            cur.execute(sql)
            result = cur.fetchall()
        except Exception as e:
            print(e)
            msg = e.__str__()
        finally:
            self.release_con(con, cur)
        return result, msg

    def op_excute(self, sql, params=None):
        result = True
        msg = ""
        try:
            con = self.get_con()
            cur = con.cursor()
            if params is not None:
                cur.execute(sql, params)
            else:
                cur.execute(sql)
            con.commit()
        except Exception as e:
            msg = e.__str__()
            print(e)
            if "con" in dir():
                con.rollback()
            result = False
        finally:
            self.release_con(con, cur)
        return result, msg

    def op_excute_many(self, sql, params):
        result = True
        msg = ""
        try:
            con = self.get_con()
            cur = con.cursor()
            cur.executemany(sql, params)
            con.commit()
        except Exception as e:
            msg = e.__str__()
            print(e)
            if "con" in dir():
                con.rollback()
            result = False
        finally:
            self.release_con(con, cur)
        return result, msg

    def op_clear_table(self, sql):
        result = True
        msg = ""
        try:
            con = self.get_con()
            cur = con.cursor()
            cur.execute(sql)
            con.commit()
        except Exception as e:
            msg = e.__str__()
            print(e)
            if "con" in dir():
                con.rollback()
            result = False
        finally:
            self.release_con(con, cur)
        return result, msg


